<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="40%"
    title="发放卡券"
    :style="{ top: '20px' }"
    :footer="null"
    destroyOnClose
  >
    <a-form
      ref="form"
      :label-col="{ span: 2 }"
      :wrapper-col="{ span: 22 }"
      :model="formData"
      :rules="rules"
    >
      <a-form-item label="卡券类型">
        <a>{{ $enums.COUPON_TYPE.getDesc(couponType) }}</a>
      </a-form-item>
      <a-form-item label="发放用户" name="allMember">
        <a-radio-group v-model:value="formData.allMember" @change="allMemberChange">
          <a-radio :value="true">全部会员</a-radio>
          <a-radio :value="false">指定会员</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        v-if="!formData.allMember"
        label=" "
        :colon="false"
        name="memberId"
        :rules="[
          {
            required: true,
            message: '请选择会员',
            validator: (rule, value, callback) => {
              if (value?.length > 0) {
                callback();
              } else {
                callback('请选择会员');
              }
            },
          },
        ]"
      >
        <member-selector v-model:value="formData.memberId" :multiple="true" :show-sum="true" />
      </a-form-item>
      <a-form-item
        label="卡券"
        name="couponItem"
        :rules="[
          {
            required: true,
            message: '请填写卡券',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (value?.length > 0) {
                callback();
              } else {
                callback('请填写卡券');
              }
            },
          },
        ]"
      >
        <vxe-grid
          ref="grid"
          resizable
          show-overflow
          highlight-hover-row
          keep-source
          row-id="id"
          height="300"
          :data="formData.couponItem"
          :columns="tableColumn"
          :toolbar-config="toolbarConfig"
        >
          <!-- 工具栏 -->
          <template #toolbar_buttons>
            <a-space>
              <a-button type="primary" @click="addCouponItem">新增</a-button>
            </a-space>
          </template>

          <!-- 发放数量 -->
          <template #couponNum_default="{ row, rowIndex }">
            <a-form-item
              :name="['couponItem', rowIndex, 'couponNum']"
              :rules="[{ required: true, message: '请输入' }]"
              no-style
            >
              <a-input-number
                style="width: 100%"
                v-model:value="row.couponNum"
                min="1"
                :precision="0"
              />
            </a-form-item>
          </template>

          <!-- 卡券类型 列自定义内容 -->
          <template #couponType_default="{ row }">
            {{ _This().$enums.COUPON_TYPE.getDesc(row.couponType) }}
          </template>

          <template #couponName_default="{ row, rowIndex }">
            <a-form-item
              :name="['couponItem', rowIndex, 'couponId']"
              :rules="[{ required: true, message: '请输入' }]"
              no-style
            >
              <coupon-selector
                :request-params="{ couponTypes: couponType }"
                v-model:value="row.couponId"
                @input-row="couponSelectorConfirm(rowIndex, $event)"
              />
            </a-form-item>
          </template>

          <!-- 发放方式 列自定义内容 -->
          <template #sendWay_default="{ row }">
            {{ _This().$enums.SEND_WAY.getDesc(row.sendWay) }}
          </template>

          <template #useCondition_default="{ row }">
            {{ row.useCondition === 0 ? '无限制' : formatAmount(row.useCondition) }}
          </template>

          <!-- 状态 列自定义内容 -->
          <template #available_default="{ row }">
            <available-tag :available="row.available" />
          </template>

          <!-- 操作 列自定义内容 -->
          <template #action_default="{ rowIndex }">
            <a-button type="link" @click="deleteCouponItem(rowIndex)" danger> 删除 </a-button>
          </template>
        </vxe-grid>
      </a-form-item>
    </a-form>
    <div class="form-modal-footer">
      <a-space>
        <a-button type="primary" :loading="loading" html-type="submit" @click="submit">
          保存
        </a-button>
        <a-button :loading="loading" @click="closeDialog">取消</a-button>
      </a-space>
    </div>
  </a-modal>
</template>

<script setup>
  import { getCurrentInstance, ref } from 'vue';
  import MemberSelector from '@/components/Selector/src/MemberSelector.vue';
  import CouponSelector from '@/components/Selector/src/CouponSelector.vue';
  import AButton from '@/components/Button/src/BasicButton.vue';
  import * as api from '@/api/base-data/member-coupon';

  const emit = defineEmits(['close']);

  // this对象
  const instance = getCurrentInstance();

  // 弹窗是否可见
  const visible = ref(false);

  const loading = ref(false);

  // 组件参数
  const props = defineProps({
    // 卡券类型
    couponType: {
      type: Number,
      required: true,
    },
  });

  const form = ref();

  const formData = ref({
    allMember: true,
    memberId: [],
    couponItem: [],
  });

  const rules = ref({});

  const allMemberChange = () => {
    formData.value.memberId = [];
  };

  const grid = ref();

  const tableColumn = ref([
    {
      field: 'couponNum',
      title: '发放数量',
      minWidth: 100,
      slots: { default: 'couponNum_default' },
    },
    {
      field: 'couponName',
      title: '卡券',
      minWidth: 150,
      slots: { default: 'couponName_default' },
    },
    {
      field: 'couponType',
      title: '卡券类型',
      minWidth: 100,
      slots: { default: 'couponType_default' },
    },
    {
      field: 'sendWay',
      title: '发放方式',
      width: 100,
      slots: { default: 'sendWay_default' },
    },
    { field: 'price', title: '售价', width: 100, formatter: (data) => formatAmount(data) },
    { field: 'parValue', title: '卡券面值', width: 100, formatter: (data) => formatAmount(data) },
    { field: 'added', title: '增值', width: 100, formatter: (data) => formatPercentage(data) },
    { field: 'effectiveDay', title: '有效期', width: 100, formatter: (data) => formatDay(data) },
    {
      field: 'useCondition',
      title: '使用条件',
      width: 100,
      slots: { default: 'useCondition_default' },
    },
    {
      field: 'available',
      title: '状态',
      width: 100,
      slots: { default: 'available_default' },
    },
    { title: '操作', width: 70, fixed: 'right', slots: { default: 'action_default' } },
  ]);

  // 工具栏配置
  const toolbarConfig = ref({
    // 缩放
    zoom: false,
    // 自定义表头
    custom: false,
    // 右侧是否显示刷新按钮
    refresh: false,
    // 自定义左侧工具栏
    slots: {
      buttons: 'toolbar_buttons',
    },
  });

  // 格式化金额
  const formatAmount = (data) => {
    let num = typeof data === 'number' ? data : data?.cellValue;
    return '￥ ' + Number.parseFloat(num || 0).toFixed(2);
  };
  // 格式化百分比
  const formatPercentage = (data) => {
    return Number.parseFloat(data?.cellValue || 0).toFixed(2) + ' %';
  };
  // 格式化日
  const formatDay = (data) => {
    let day = Number.parseFloat(data?.cellValue || 0);
    return day ? day + ' 天' : '永久';
  };

  // 添加卡券项
  const addCouponItem = () => {
    formData.value.couponItem.push({
      couponNum: 1,
    });
  };

  // 删除卡券项
  const deleteCouponItem = (rowIndex) => {
    formData.value.couponItem.splice(rowIndex, 1);
  };

  const couponSelectorConfirm = (rowIndex, row) => {
    formData.value.couponItem[rowIndex] = {
      available: row?.available,
      couponName: row?.couponName,
      couponType: row?.couponType,
      effectiveDay: row?.effectiveDay,
      parValue: row?.parValue,
      price: row?.price,
      sendWay: row?.sendWay,
      useCondition: row?.useCondition,
      couponId: row?.id,
      couponNum: formData.value.couponItem[rowIndex].couponNum,
    };
    grid.value.reloadData(formData.value.couponItem);
  };

  const submit = () => {
    Promise.allSettled([form.value.validate()]).then((results) => {
      console.log(results);
      if (results[0].status === 'fulfilled') {
        loading.value = true;
        api
          .couponGrant({
            allMember: formData.value.allMember,
            memberId: formData.value.memberId,
            couponItem: formData.value.couponItem.map((item) => {
              return {
                couponNum: item.couponNum,
                couponId: item.couponId,
              };
            }),
          })
          .then(() => {
            _This().$msg.createSuccess('发卡成功！');
            closeDialog();
          })
          .finally(() => (loading.value = false));
      }
    });
  };

  // 打开弹窗
  const openDialog = () => {
    visible.value = true;
    initFormData();
  };

  // 关闭弹窗
  const closeDialog = () => {
    visible.value = false;
    emit('close');
  };

  const initFormData = () => {
    formData.value = {
      allMember: true,
      memberId: [],
      couponItem: [],
    };
  };

  // 组件实例对象
  const _This = () => {
    return instance.appContext.config.globalProperties;
  };

  defineExpose({
    openDialog,
  });
</script>

<style scoped></style>
